<template>
  <div class="workflow-form-page">
    <h2>表单定义管理</h2>
    <el-button type="primary" @click="onAdd" v-if="hasPermission(WorkflowAuth.FORM_ADD)">新建表单</el-button>
    <el-button type="success" @click="goToFormBuilder" style="margin-left: 8px;">表单设计器</el-button>
    <el-table :data="tableData" :loading="loading" style="width: 100%" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="表单名称" />
      <el-table-column prop="formKey" label="表单编码" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button size="small" @click="onEdit(scope.row)" v-if="scope.row && hasPermission(WorkflowAuth.FORM_EDIT)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(scope.row)" v-if="scope.row && hasPermission(WorkflowAuth.FORM_DEL)">删除</el-button>
          <el-button size="small" @click="onDesign(scope.row)" v-if="scope.row && hasPermission(WorkflowAuth.FORM_EDIT)">设计表单</el-button>
          <el-button size="small" type="warning" v-if="scope.row && hasPermission(WorkflowAuth.FORM_PUBLISH_PUBLIC) && scope.row.tenantId !== 0" @click="onPublishPublic(scope.row)">发布为公共数据</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :total="total"
      @current-change="fetchList"
      @size-change="fetchList"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      style="margin-top: 16px;"
    />
    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="editVisible" :title="dialogTitle" width="400px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="表单名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入表单名称" />
        </el-form-item>
        <el-form-item label="表单编码" prop="code">
          <el-input v-model="editForm.code" placeholder="请输入表单编码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="启用" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="onEditSave">保存</el-button>
      </template>
    </el-dialog>
    <!-- 保留 schema 粘贴和保存弹窗，为后续集成 Variant Form 做准备 -->
    <el-dialog v-model="formBuilderVisible" title="表单设计器" width="90vw" :close-on-click-modal="false" :destroy-on-close="true">
      <FormBuilder v-model="formBuilderSchema" style="height:75vh;" />
      <template #footer>
        <el-button @click="onFormBuilderCancel">取消</el-button>
        <el-button type="primary" @click="onFormBuilderSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getFormList, addForm, editForm, deleteForms, getFormDetail } from '@/api/workflow/form.api'
import { WorkflowAuth } from '@/auth/workflow/workflow.auth'
import { usePermission } from '@/hooks/web/usePermission'
import { defHttp } from '@/utils/http/axios'
import { ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import FormBuilder from './form-builder.vue'

// 引入统一的夜间模式样式
import '@/components/Workflow/styles/dark-theme.css'

const tableData = ref([])
const loading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])
const router = useRouter()

const editVisible = ref(false)
const userTenantId = 1 // TODO: 替换为实际登录用户租户ID
const editForm = ref({ name: '', code: '', formKey: '', status: '0' })
const editFormRef = ref()
const editRules = {
  name: [{ required: true, message: '请输入表单名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入表单编码', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}
const dialogTitle = ref('')
const editingId = ref<number|null>(null)

const formBuilderVisible = ref(false)
const formBuilderSchema = ref({})
const formBuilderRow = ref<any>(null)

function fetchList() {
  loading.value = true
  getFormList({ pageNum: pageNum.value, pageSize: pageSize.value }).then(res => {
    tableData.value = res?.items || []
    total.value = res?.total || 0
  }).finally(() => loading.value = false)
}
function onSelectionChange(val) { selectedRows.value = val }
function onAdd() {
  dialogTitle.value = '新建表单'
  editForm.value = { name: '', code: '', formKey: '', status: '0' }
  editingId.value = null
  editVisible.value = true
}
function onEdit(row) {
  dialogTitle.value = '编辑表单'
  getFormDetail(row.id).then(res => {
    editForm.value = { ...res.data }
    editingId.value = row.id
    editVisible.value = true
  })
}
function onEditSave() {
  editFormRef.value.validate((valid) => {
    if (!valid) return
    const data = { ...editForm.value }
    if (editingId.value) {
      editForm({ ...data, id: editingId.value }).then(() => {
        editVisible.value = false
        fetchList()
      })
    } else {
      addForm(data).then(() => {
        editVisible.value = false
        fetchList()
      })
    }
  })
}
function onDelete(row) {
  deleteForms([row.id]).then(fetchList)
}
function onDesign(row) {
  router.push({ path: '/workflow/form/builder', query: { ...row } })
}
async function onFormBuilderSave() {
  const schemaObj = formBuilderSchema.value
  if (formBuilderRow.value?.id) {
    await editForm({ ...formBuilderRow.value, schema: schemaObj, id: formBuilderRow.value.id })
  }
  formBuilderVisible.value = false
  ElMessage.success('保存成功')
  fetchList()
}
function onFormBuilderCancel() {
  formBuilderVisible.value = false
  formBuilderSchema.value = {}
  formBuilderRow.value = null
}
function onPublishPublic(row) {
  ElMessageBox.confirm('确定要将该表单发布为公共数据吗？', '提示', {
    type: 'warning'
  }).then(() => {
    defHttp.post({ url: `/form/publishPublic/${row.id}` }).then(() => {
      ElMessage.success('发布成功')
      fetchList()
    })
  })
}
function hasPermission(code) {
  // TODO: 替换为实际权限校验逻辑
  return true
}
function goToFormBuilder() {
  router.push({ path: '/workflow/form/builder' })
}
onMounted(fetchList)
</script>
<style scoped>
.workflow-form-page { padding: 24px; }
</style>
